package br.fot.granola.oboe.util;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.view.KeyEvent;
import br.fot.granola.oboe.core.Oboe;
import br.fot.granola.oboe.core.Slot;
import br.fot.granola.oboe.graphics.camera.Camera;
import br.fot.granola.oboe.graphics.camera.CameraBackend;

public class OboeRenderer extends GLSurfaceView implements Renderer
{
	private String name;
	private Camera camera;
	private boolean isFirst;
	private static final Hashtable< String, OboeRenderer > rendererIndex = new Hashtable<String, OboeRenderer>();
	private OGLVersion oglVersion;
	
	public OboeRenderer( Context ctx, String name, OGLVersion glv )
	{
		super( ctx );
		this.setRenderer( this );
		this.requestFocus();
		this.setFocusableInTouchMode(true);
		this.name = name;
		this.isFirst = rendererIndex.size() == 0;
		this.oglVersion = glv;
		
		if( rendererIndex.containsKey(name) )
		{
			int c=1;
			do
			{
				c++;
				this.name = name + c;
			}while( rendererIndex.containsKey(name) );
		}
		
		rendererIndex.put( this.name, this );
	}
	
	public void setCamera( Camera cam )
	{
		this.camera = cam;
	}
	
	public static OboeRenderer getRenderer( String name )
	{
		return rendererIndex.get( name );
	}
	
	public static Enumeration<String> getRendererList()
	{
		return rendererIndex.keys();
	}
	
	@Slot public void onDelete()
	{
		rendererIndex.remove( this.name );
	}

	public void onSurfaceCreated( GL10 gl, EGLConfig config )
	{
		if( this.camera != null )
		{
			this.camera.getBackend().created( this.camera, gl );
		}
	}
	
	@Override public boolean onKeyUp( int keyCode, KeyEvent event )
	{
		Oboe.signalUp( this, "onKeyUp", keyCode );
		return true;
	}
	
	@Override public boolean onKeyDown( int keyCode, KeyEvent event )
	{
		Oboe.signalUp( this, "onKeyDown", keyCode );
		return true;
	}
	
	public void onDrawFrame( GL10 gl )
	{
		if( this.isFirst ) Oboe.signalUp( this, "onUpdate" );
		
		if( this.camera == null || this.camera.parentScene == null ) return;
		
		this.camera.getBackend().draw( this.camera, gl);
	}
	
	public void onSurfaceChanged( GL10 gl, int width, int height )
	{
		if( this.camera != null )
		{
			((CameraBackend)this.camera.getBackend()).viewChanged( this.camera, gl, width, height);
		}
	}
	
}
